package com.zomiot.portal.aichat.controller;

import com.zomiot.portal.aichat.service.AiService;
//import com.zomiot.portal.aichat.service.RagService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.Map;

/**
 * @ClassName ChatController
 * @Author 阿⭐
 * @Date 2025/11/5 15:50
 * @Description TODO
 */
@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class ChatController {

//    private final RagService ragService;

    private final AiService aiService;

//    @PostMapping(value = "/ragAsk", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    public Flux<ServerSentEvent<String>> ragAsk(@RequestBody Map<String, String> body) {
//        return ragService.ask(body.get("question"))
//                .scan("", (acc, cur) -> acc + cur)
//                .map(full -> ServerSentEvent.<String>builder()
//                        .data(full)
//                        .event("message")
//                        .build());
//    }

    @PostMapping(value = "/ask", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> ask(@RequestBody Map<String, String> body) {
        try{
            String question = body.get("question");
            return aiService.ask(question)
                    .map(content -> ServerSentEvent.builder(content)
                            .event("message")
                            .build());
        }catch (Exception e){
            if(e.getMessage().equalsIgnoreCase("Too Many Requests")){
                String question = body.get("question");
                if (question.equalsIgnoreCase("地址")){
                    return Flux.just(ServerSentEvent.builder("厦门市湖里区金钟路 3 号 1706-2。")
                            .event("message")
                            .build());
                }
            }
        }

        return Flux.just(ServerSentEvent.builder("AI繁忙，请稍后重试")
                .event("message")
                .build());
    }
}
